import Animation from '../base/animation';
import { SCREEN_WIDTH, SCREEN_HEIGHT } from '../render';

const ENEMY_IMG_SRC = 'images/enemy.png';
const ENEMY_WIDTH = 60;
const ENEMY_HEIGHT = 60;
const EXPLO_IMG_PREFIX = 'images/explosion';

export default class Enemy extends Animation {
  speed = Math.random() * 0.5; // 飞行速度
  HP = Math.random() * 100 + 50; // 生命值
  damageSource = []; // 伤害来源

  constructor() {
    super(ENEMY_IMG_SRC, ENEMY_WIDTH, ENEMY_HEIGHT);
  }

  init() {
    this.x = this.getRandomX()
    this.y = -this.height;
    this.id = Math.random().toString(36).substr(2, 9);

    this.isActive = true;
    this.visible = true;

    // 被子弹命中之后可能会有的状态
    this.frozenSecond = 0;   // 剩余冻结时长
    this.frozenDamageAmplification = 0; // 冻结状态下的伤害加成
    this.burnedSecond = 0;   // 剩余点燃时长，持续扣血
    this.burnedDamageAmplification = 0; // 点燃状态下的伤害
    this.poisonedSecond = 0; // 剩余中毒时长，减速
    this.poisonedDamageAmplification = 0; // 中毒状态下的伤害加成

    // 设置爆炸动画
    this.initExplosionAnimation();

    this.HP = this.HP * (GameGlobal.databus.turn.index + 0.15); // 回合血量倍率
  }

  // 生成随机 X 坐标
  getRandomX() {
    return Math.floor(Math.random() * (SCREEN_WIDTH - ENEMY_WIDTH));
  }

  // 预定义爆炸的帧动画
  initExplosionAnimation() {
    const EXPLO_FRAME_COUNT = 19;
    const frames = Array.from(
      { length: EXPLO_FRAME_COUNT },
      (_, i) => `${EXPLO_IMG_PREFIX}${i + 1}.png`
    );
    this.initFrames(frames);
  }

  updateIfFrozen() {
    // todo 绘制冻结效果
  }

  updateIfBurned() {
    // todo 绘制燃烧效果
    this.y += this.speed;
  }

  updateIfPoisoned() {
    // todo 绘制中毒效果
    this.y += this.speed * 0.5;
  }

  // 每一帧更新敌人位置
  update() {
    if (GameGlobal.databus.isGameOver) {
      return;
    }

    if(this.frozen){
      this.updateIfFrozen();
    }
    else{
      this.y += this.speed;
    }

    // 对象回收
    if (this.y > SCREEN_HEIGHT + this.height) {
      this.remove();
    }
  }

  // 受到攻击，同一子弹无法对同一敌人重复造成伤害
  hurt(bullet) {
    if (this.damageSource.includes(bullet.id)) {
      return;
    }
    else{
      this.HP -= bullet.damage;
      this.damageSource.push(bullet.id);
      if (this.HP <= 0) {
        this.destroy();
        GameGlobal.databus.score += 1; // 增加分数
      }
      // 子弹剩余穿透为0，则销毁子弹
      if (bullet.penetration <= 0) {
        bullet.destroy(); // 销毁子弹
      } else {
        bullet.penetration--; // 穿透-1
      }
    }
  }

  // 销毁敌人
  destroy() {
    this.isActive = false;
    // 播放销毁动画后移除
    this.playAnimation();
    GameGlobal.musicManager.playExplosion(); // 播放爆炸音效
    // wx.vibrateShort({
    //   type: 'light'
    // }); // 轻微震动
    this.on('stopAnimation', () => this.remove.bind(this));
  }

  remove() {
    this.isActive = false;
    this.visible = false;
    GameGlobal.databus.removeEnemy(this);
  }
}
